#!/bin/bash
# Redis 主从部署脚本

set -e

echo "=========================================="
echo "部署 Redis 主从集群"
echo "=========================================="

# 检查 kubectl 是否可用
if ! command -v kubectl &> /dev/null; then
    echo "错误: kubectl 未安装或不在 PATH 中"
    exit 1
fi

# 设置 KUBECONFIG 环境变量（k3s 配置）
if [ -f /etc/rancher/k3s/k3s.yaml ]; then
    export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
elif [ -f ~/.kube/config ]; then
    export KUBECONFIG=~/.kube/config
elif [ -f /root/.kube/config ]; then
    export KUBECONFIG=/root/.kube/config
fi

# 1. 确保数据目录权限正确
echo "[1/5] 检查数据目录权限..."
if [ -d /data/redis ]; then
    chown -R 999:999 /data/redis 2>/dev/null || echo "警告: 无法设置目录权限（可能需要 root）"
    chmod -R 750 /data/redis 2>/dev/null || echo "警告: 无法设置目录权限（可能需要 root）"
    echo "✓ 数据目录权限已检查"
else
    echo "警告: /data/redis 不存在，请先运行 prepare-storage.sh"
fi

# 2. 部署 Redis 主节点
echo "[2/5] 部署 Redis 主节点..."
echo "  创建 ConfigMap..."
kubectl apply -f k8s/redis/master/configmap.yaml

echo "  创建 Secret..."
kubectl apply -f k8s/redis/master/secret.yaml

echo "  创建 PVC..."
kubectl apply -f k8s/redis/master/pvc.yaml

echo "  注意: PVC 将在 Pod 调度后自动绑定（WaitForFirstConsumer 模式）"

echo "  部署 StatefulSet..."
kubectl apply -f k8s/redis/master/statefulset.yaml

echo "  创建 Service..."
kubectl apply -f k8s/redis/master/service.yaml

# 等待主节点就绪
echo ""
echo "等待 Redis 主节点启动..."
kubectl wait --for=condition=ready pod -l app=redis,role=master --timeout=300s

# 3. 部署 Redis 从节点
echo ""
echo "[3/5] 部署 Redis 从节点..."
echo "  创建 ConfigMap..."
kubectl apply -f k8s/redis/slave/configmap.yaml

echo "  部署 StatefulSet..."
kubectl apply -f k8s/redis/slave/statefulset.yaml

echo "  创建 Service..."
kubectl apply -f k8s/redis/slave/service.yaml

# 等待从节点就绪
echo ""
echo "等待 Redis 从节点启动..."
kubectl wait --for=condition=ready pod -l app=redis,role=slave --timeout=300s

# 4. 验证主从复制
echo ""
echo "[4/5] 验证主从复制..."
sleep 10

MASTER_POD=$(kubectl get pod -l app=redis,role=master -o jsonpath='{.items[0].metadata.name}')
SLAVE_POD=$(kubectl get pod -l app=redis,role=slave -o jsonpath='{.items[0].metadata.name}')

echo "  在主节点设置测试键..."
kubectl exec $MASTER_POD -- redis-cli set test-key "test-value"

echo "  在从节点读取测试键..."
kubectl exec $SLAVE_POD -- redis-cli get test-key

# 5. 显示状态
echo ""
echo "[5/5] Redis 部署状态"
echo "=========================================="
kubectl get pods -l app=redis
kubectl get svc -l app=redis

echo ""
echo "=========================================="
echo "Redis 主从集群部署完成！"
echo "=========================================="
echo ""
echo "连接信息："
echo "  主节点 ClusterIP: redis-master:6379"
echo "  主节点 NodePort: <节点IP>:30637"
echo "  从节点 ClusterIP: redis-slave:6379"
echo "  从节点 NodePort: <节点IP>:30638"
echo ""
echo "测试连接："
echo "  kubectl run -it --rm redis-client --image=redis:7-alpine --restart=Never -- redis-cli -h redis-master"

